# -*- coding: utf-8 -*-

import copy
from pprint import pprint as pp

try:
    from Products.CapWorkBook.config import NOTE_VIA_RANK_OVERRIDE
except:
    NOTE_VIA_RANK_OVERRIDE = 'Note: The overall target viability rank is derived using one or more user override ranks.'

DEBUG = 0

def convertMiradiToConProDataDict( miradi_data_dict ):

    # Keep variables outside of loops. These variables contain ALL the data for the tables in the database.
    all_data                            = {}
    project_info                        = {}
    countries_info                      = []
    ous_info                            = []
    ecoregion_info                      = []
    classification_info                 = []
    kea_info                            = []
    target_info                         = []
    t_hab_info                          = []
    nested_target_info                  = []
    strat_act_threats_info              = []
    stress_info                         = []
    stress_threat_info                  = []
    threat_target_assocs_info           = []
    viability_assocs_info               = []
    threat_info                         = []
    threat_indicator_info               = []
    objective_info                      = []
    objective_indicator_info            = []
    percent_complete_measures_info      = []
    obj_percent_complete_assoc_info     = []
    strategy_info                       = []
    impl_status_info                    = []
    s_a_status_association_info         = []
    objectives_strategies_info          = []
    activities_info                     = []
    step_status_association_info        = []
    indicator_info                      = []
    other_info                          = []
    indicators_other_info               = []
    indicator_measure_info              = []
    indicator_methods_associations_info = []
    indicator_status_association_info   = []
    method_info                         = []

    #PROJECTS table
    curr_branch = miradi_data_dict['project_info'][0]
    project_struct_info = {  'project_id'               : 'PROJECT_ID',
                             'shareable'                : 'SHARE_OUTSIDE_TNC',
                             'project_name'             : 'PROJECT_NAME',
                             'start_date'               : 'PROJECT_START_DATE',
                             'data_effective_date'      : 'DATA_EFFECTIVE_DATE',
                             'latitude'                 : 'LATITUDE',
                             'longitude'                : 'LONGITUDE',
                             'givenname'                : 'CONTACT_FNAME',
                             'surname'                  : 'CONTACT_LNAME',
                             'email'                    : 'CONTACT_EMAIL',
                             'phone'                    : 'CONTACT_TELEPHONE',
                             'organization'             : 'CONTACT_ORGANIZATION',
                             'description_comment'      : 'PROJECT_DESCR_COMMENT',
                             'goal_comment'             : 'PROJECT_GOAL_COMMENT',
                             'hectares'                 : 'PROJECT_AREA_SIZE_HECTARES',
                             'planning_team_comment'    : 'PLANNING_TEAM_COMMENT',
                             'lessons_learned'          : 'PROJECT_LESSONS_LEARNED',
                             'related_projects'         : 'ASSOC_PROJECTS_COMMENT',
                             'stressless_threat_rank'   : 'STRESSLESS_THREAT_RANK',
                             'project_threat_rank'      : 'PROJECT_THREAT_RANK',
                             'project_viability_rank'   : 'PROJECT_VIA_RANK',
                             'exporter_version'         : 'WKBK_VERSION',
                             }
    for proj_item in project_struct_info.keys():
        if curr_branch.has_key(proj_item):
            # if curr_branch[proj_item] evals to true, then store.... we don't want empty strings and such.
            if curr_branch[proj_item]:
                project_info[project_struct_info[proj_item]] = curr_branch[proj_item]

            # Exceptions to normal handling here
            ## SHAREABLE
            if proj_item == 'shareable':
                if curr_branch['shareable'].lower() == 'false':
                    project_info[project_struct_info[proj_item]] = 'NO'
                elif curr_branch['shareable'].lower() == 'true':
                    project_info[project_struct_info['shareable']] = 'YES'
                elif curr_branch['shareable'] == '0':
                    project_info[project_struct_info[proj_item]] = 'NO'
                elif curr_branch['shareable'] == '1':
                    project_info[project_struct_info['shareable']] = 'YES'
                else:
                    # Default to not sharable if we cannot clearly determine otherwise.
                    project_info[project_struct_info[proj_item]] = 'NO'

            ## exporter_version
            if proj_item == 'exporter_version':
                if curr_branch['exporter_version']:
                    project_info[project_struct_info['exporter_version']] = 'Miradi %s' % curr_branch['exporter_version']
                else:
                    project_info[project_struct_info['exporter_version']] = 'Miradi - No version specified'

    #PROJECT_COUNTRIES table
    countries = curr_branch['country_codes']
    for country in countries:
        if country:
            countries_info.append({'COUNTRY_CODE':country})


    #PROJECT_OU
    ous = curr_branch['ou_codes']
    for ou in ous:
        if ou:
            ous_info.append({'PROJECT_OU_ID':ou})


    #PROJECT_ECOREGIONS
    ecoregions = curr_branch['ecoregion_codes']
    for ecoregion in ecoregions:
        if ecoregion:
            ecoregion_info.append({'ECOREGION_CODE':ecoregion})


    #PROJECT_CLASS_ASSOCIATION
    classifications = curr_branch['classification_ids']
    for classification in classifications:
        if classification:
            classification_info.append({'PROJECT_CLASS_NAME_ID':classification})


    #KEY_ATTRIBUTES
    keas = miradi_data_dict['keas']
    kea_struct_info = { 'id':'KEY_ATTRIBUTE_WID',
                        'category':'CATEGORY_NAME',
                        'name':'KEY_ATTRIBUTE_NAME',
                        }
    for kea in keas:
        tmp_kea = {}
        for kea_item in kea_struct_info.keys():
            if kea.has_key(kea_item):
                # if kea[kea_item] evals to true, then record.... we don't want empty strings.
                if kea[kea_item]:
                    tmp_kea['SHARED_KEA_WID'] = kea['id'] # Per dberg: This is needed for CAP but to be compatable, make same as id!
                    tmp_kea[kea_struct_info[kea_item]] = kea[kea_item]
        kea_info.append(tmp_kea)

    #PROJECT_TARGETS
    targets = miradi_data_dict['targets']
    target_struct_info = {  'id'                        : 'TARGET_WID',
                            'sequence'                  : 'TARGET_SEQ',
                            'name'                      : 'TARGET_NAME',
                            'description'               : 'FOCAL_TARGET_DESC',
                            'description_comment'       : 'FOCAL_TARGET_DESC_COMMENT',
                            'target_viability_comment'  : 'TARGET_VIABILITY_COMMENT',
                            'target_viability_rank'     : 'TARGET_VIABILITY_RANK',
                            }
    for target in targets:
        curr_target_id = target['id']
        tmp_target = {}
        for target_item in target_struct_info.keys():

            # XXX EBC: Paul, what are your thoughts here? Line 158 doesn't need to be executed with every iteration.
            #

            if target.has_key(target_item):
                # if target[target_item] evals to true, then fetch the data.... we don't want empty records!
                if target[target_item]:
                    #Exceptions
                    if target['target_viability_mode'] == 'simple':
                        #Note from Dan Salzer:
                        #   If the user has set the viability mode to Simple for a particular target,
                        #   the Miradi Overall Target Viability Rank for that target should be used to
                        #   populate both the ConPro Overall Target Viability Rank and the Condition
                        #   Override Rank.
                        # So, in addition to storing the value in PROJECT_TARGETS.TARGET_VIABILITY_RANK
                        # adding it to the override value of condition at PROJECT_TARGETS.CONDITION_OVRD_RANK
                        #
                        tmp_target['CONDITION_OVRD_RANK'] = target['target_viability_rank']
                        tmp_target['CONDITION_WGT'] = '1'
                        # If NOTE_VIA_RANK_OVERRIDE is not a part of the comment, add it.
                        try:
                            tmp_val = target['target_viability_comment']
                        except:
                            tmp_val = ''
                        if NOTE_VIA_RANK_OVERRIDE not in tmp_val:
                            tmp_target[target_struct_info['target_viability_comment']] = "%s  %s" % (tmp_val,NOTE_VIA_RANK_OVERRIDE)
                    tmp_target[target_struct_info[target_item]] = target[target_item]
        target_info.append(tmp_target)


        #PROJECT_HABITATS
        habitat_taxonomy_codes = target['habitat_taxonomy_codes']
        for habitat_taxonomy_code in habitat_taxonomy_codes:
            if habitat_taxonomy_code:
                t_hab_info.append( {'TARGET_WID':curr_target_id,'HABITAT_ASSOCIATION_CODE':habitat_taxonomy_code} )


        #NESTED_TARGETS
        nested_targets = target['nested_targets']
        nest_t_struct_info = {   'sequence' : 'NESTED_TARGET_SEQ',
                                 'name'     : 'NESTED_TARGET_NAME',
                                 'comment'  : 'NESTED_TARGET_COMMENT',
                                 }
        for nested_target in nested_targets:
            tmp_nested_target = {}
            for nest_t_struct_key in nest_t_struct_info.keys():
                if nested_target[nest_t_struct_key]:
                    tmp_nested_target['TARGET_WID'] = curr_target_id
                    tmp_nested_target[nest_t_struct_info[nest_t_struct_key]] = nested_target[nest_t_struct_key]
            nested_target_info.append(tmp_nested_target)


        #STRATEGIC_ACTION_THREATS
        strategy_threat_target_assocs = target['strategy_threat_target_assocs']
        strat_act_threats_struct_info = {   'strategy_id'   : 'STRATEGIC_ACTION_WID',
                                            'threat_id'     : 'THREAT_WID',
                                            }
        for strategy_threat_target_assoc in strategy_threat_target_assocs:
            tmp_strat_act_threats = {}
            for strat_act_threats_key in strat_act_threats_struct_info.keys():
                if strategy_threat_target_assoc.has_key(strat_act_threats_key):
                    if strategy_threat_target_assoc[strat_act_threats_key]:
                        tmp_strat_act_threats['TARGET_WID'] = curr_target_id
                        tmp_strat_act_threats[strat_act_threats_struct_info[strat_act_threats_key]] = strategy_threat_target_assoc[strat_act_threats_key]
            strat_act_threats_info.append(tmp_strat_act_threats)


        #STRESSES_TARGET
        stresses = target['stresses']
        stresses_struct_info = {'sequence'      : 'STRESS_TARGET_SEQ',
                                'name'          : 'STRESS_NAME',
                                'severity'      : 'STRESS_SEVERITY',
                                'scope'         : 'STRESS_SCOPE',
                                'to_target_rank': 'STRESS_TO_TARGET_RANK',
                                }
        for stress in stresses:
            tmp_stress = {}
            for stresses_struct_key in stresses_struct_info.keys():
                if stress.has_key(stresses_struct_key):
                    if stress[stresses_struct_key]:
                        tmp_stress['TARGET_WID'] = curr_target_id
                        tmp_stress[stresses_struct_info[stresses_struct_key]] = stress[stresses_struct_key]
            if tmp_stress:
                stress_info.append(tmp_stress)


            #STRESS_THREAT
            stresses_threats = stress['to_threat_ratings']
            stress_threat_struct_info = {   'threat_id'                     : 'THREAT_TARGET_SEQ',
                                            'contrib_rank'                  : 'S_T_CONTRIB_RANK',
                                            'irreversible_rank'             : 'S_T_IRREVERSIBLE_RANK',
                                            'stress_threat_to_target_rank'  : 'S_T_TO_TARGET_RANK',
                                            }
            for stress_threat in stresses_threats:
                tmp_stress_threat = {}
                for stress_threat_struct_key in stress_threat_struct_info.keys():
                    if stress_threat[stress_threat_struct_key]:
                        tmp_stress_threat['TARGET_WID'] = curr_target_id
                        tmp_stress_threat['THREAT_TARGET_SEQ'] = stress_threat['threat_id']
                        tmp_stress_threat['STRESS_TARGET_SEQ'] = stress['sequence']
                        tmp_stress_threat[stress_threat_struct_info[stress_threat_struct_key]] = stress_threat[stress_threat_struct_key]
                stress_threat_info.append(tmp_stress_threat)


        #THREAT_TARGET
        threat_target_assocs = target['threat_target_assocs']
        threat_target_assocs_struct_info = {'threat_id'             :'THREAT_WID',
                                            'threat_to_target_rank' :'THREAT_TO_TARGET_RANK',
                                            'severity'              :'THREAT_SEVERITY',
                                            'scope'                 :'THREAT_SCOPE',
                                            'irreversibility'       :'THREAT_IRREVERSIBILITY',
                                            'comment'               :'THREAT_TARGET_COMMENT',
                                            }
        for threat_target_assoc in threat_target_assocs:
            tmp_threat_target_assocs = {}
            for threat_target_assocs_struct_key in threat_target_assocs_struct_info.keys():
                if threat_target_assoc.has_key(threat_target_assocs_struct_key):
                    if threat_target_assoc[threat_target_assocs_struct_key]:
                        tmp_threat_target_assocs['TARGET_WID'] = curr_target_id
                        tmp_threat_target_assocs['THREAT_TARGET_SEQ'] = threat_target_assoc['threat_id']
                        tmp_threat_target_assocs[threat_target_assocs_struct_info[threat_target_assocs_struct_key]] = threat_target_assoc[threat_target_assocs_struct_key]
            threat_target_assocs_info.append(tmp_threat_target_assocs)


    #VIABILITY
    viability_count = 1
    viability_assessments = miradi_data_dict['viability_assessments']
    viability_struct_info = {   'target_id'                         :'TARGET_WID',
                                'indicator_id'                      :'INDICATOR_WID',
                                'kea_id'                            :'KEY_ATTRIBUTE_WID',
                                'indicator_description_poor'        :'INDICATOR_DESC_POOR',
                                'indicator_description_fair'        :'INDICATOR_DESC_FAIR',
                                'indicator_description_good'        :'INDICATOR_DESC_GOOD',
                                'indicator_description_very_good'   :'INDICATOR_DESC_VERY_GOOD',
                                'source_indicator_ratings'          :'SOURCE_IND_RATINGS',
                                'desired_viability_rating'          :'DSRD_VIABILITY_RATING',
                                'desired_rating_date'               :'DSRD_RATING_DATE',
                                'kea_and_indicator_comment'         :'ATTR_AND_IND_COMMENT',
                                'indicator_rating_comment'          :'IND_RATINGS_COMMENT',
                                'desired_rating_comment'            :'DSRD_RATING_COMMENT',
                                }

    for viability_assessment in viability_assessments:
        tmp_viability = {}
        for viability_struct_key in viability_struct_info.keys():
            if viability_assessment.has_key(viability_struct_key):
                if viability_assessment[viability_struct_key]:
                    tmp_viability['VIABILITY_WID'] = str( viability_count )
                    tmp_viability[viability_struct_info[viability_struct_key]] = viability_assessment[viability_struct_key]
        viability_assocs_info.append(tmp_viability)
        viability_count += 1


    #THREATS (actual table name is PROJECT_THREATS)
    threat_indicator_count = 1
    threats = miradi_data_dict['threats']
    threat_struct_info = {  'id'                    :'THREAT_WID',
                            'name'                  :'THREAT_NAME',
                            'threat_taxonomy_code'  :'THREAT_TAXONOMY_CODE',
                            'threat_to_project_rank':'THREAT_TO_PROJ_RANK',
                            }
    for threat in threats:
        tmp_threat = {}
        for threat_struct_key in threat_struct_info.keys():
            if threat.has_key(threat_struct_key):
                if threat[threat_struct_key]:
                    tmp_threat['THREAT_RANK_SEQ'] = threat['id']
                    tmp_threat[threat_struct_info[threat_struct_key]] = threat[threat_struct_key]
        threat_info.append(tmp_threat)

        #INDICATOR_THREATS
        threat_indicators = threat['indicator_ids']
        for threat_indicator in threat_indicators:
            if threat_indicator:
                threat_indicator_info.append({  'THREAT_WID'            : threat['id'],
                                                'INDICATOR_WID'         : threat_indicator,
                                                'INDICATOR_THREAT_WID'  : threat_indicator_count,
                                                })
                threat_indicator_count += 1


    #PROJECT_OBJECTIVES - also process objective indicators and percent complete measures
    objective_indicator_count = 1
    objectives = miradi_data_dict['objectives']
    objective_struct_info = {   'id'        : 'OBJECTIVE_WID',
                                'name'      : 'OBJECTIVE_NAME',
                                'comment'   : 'OBJECTIVE_COMMENT',
                                }
    percent_complete_struct_info = {'sequence'  : 'PCT_COMPLETE_WID',
                                    'measure'   : 'PCT_COMPLETE_MEASURE',
                                    'date'      : 'PCT_COMPLETE_DATE',
                                    'comment'   : 'PCT_COMPLETE_COMMENT',
                                    }
    for objective in objectives:
        tmp_objective = {}
        for objective_struct_key in objective_struct_info:
            if objective.has_key(objective_struct_key):
                if objective[objective_struct_key]:
                    tmp_objective['PRINT_ORDER'] = objective['id']
                    tmp_objective[objective_struct_info[objective_struct_key]] = objective[objective_struct_key]
        objective_info.append(tmp_objective)

        #OBJECTIVE_INDICATORS
        objective_indicators = objective['indicator_ids']
        for objective_indicator in objective_indicators:
            if objective_indicator:
                objective_indicator_info.append({   'OBJ_IND_ASSOC_WID' : objective_indicator_count,
                                                    'OBJECTIVE_WID'     : objective['id'],
                                                    'INDICATOR_WID'     : objective_indicator,
                                                    })
                objective_indicator_count += 1

        #PCT_COMPLETE
        percent_complete_measures = objective['percent_complete_measures']
        for percent_complete_measure in percent_complete_measures:
            tmp_percent_complete = {}
            for percent_complete_struct_key in percent_complete_struct_info:
                if percent_complete_measure.has_key(percent_complete_struct_key):
                    if percent_complete_measure[percent_complete_struct_key]:
                        tmp_percent_complete[percent_complete_struct_info[percent_complete_struct_key]] = percent_complete_measure[percent_complete_struct_key]
            percent_complete_measures_info.append(tmp_percent_complete)
            #OBJ_PCT_COMPLETE_ASSOCIATIONS
            obj_percent_complete_assoc_info.append({'OBJECTIVE_WID'     : objective['id'],
                                                    'PCT_COMPLETE_WID'  : percent_complete_measure['sequence'],
                                                    })


    #STRATEGIC_ACTIONS - also process strategic action activities and statuses.
    strategies = miradi_data_dict['strategies']
    strategy_struct_info = {'id'            : 'STRATEGIC_ACTION_WID',
                            'name'          : 'S_A_NAME',
                            'taxonomy_code' : 'S_A_TAXONOMY_CODE',
                            'selected'      : 'S_A_SELECTED',
                            'comment'       : 'S_A_COMMENT',
                            'total_cost'    : 'S_A_TOTAL_COST',
                            }
    impl_status_struct_info = { 'sequence'  : 'IMPL_STATUS_WID',
                                'measure'   : 'IMPL_STATUS_MEASURE',
                                'date'      : 'IMPL_STATUS_DATE',
                                'comment'   : 'IMPL_STATUS_COMMENT',
                                }
    #XXX PA: Ask Eric why we have the 'id' key in actions_struct_info below since this is not parsed out of the XML in the tear down.
    #        The value is assigned from a counter variable below.
    actions_struct_info = { 'id'            : 'STEP_WID',
                            'name'          : 'STEP_NAME',
                            'start_date'    : 'STEP_START_DATE',
                            'end_date'      : 'STEP_END_DATE',
                            'total_cost'    : 'STEP_TOTAL_COST',
                            'detail'        : 'STEP_COMMENT',
                            }

    obj_strat_wid_count = 1
    actions_count = 1
    for strategy in strategies:
        # STRATEGIC_ACTIONS
        tmp_strategy = {}
        for strategy_struct_key in strategy_struct_info.keys():
            if strategy.has_key(strategy_struct_key):
                if strategy[strategy_struct_key]:
                    tmp_strategy[strategy_struct_info[strategy_struct_key]] = strategy[strategy_struct_key]
        strategy_info.append(tmp_strategy)

        # IMPL_STATUS ( STRATEGIC_ACTIONS entries into IMPL_STATUS for require associations in S_A_STATUS_ASSOCIATIONS!!!!!! )
        strategy_statuses = strategy['statuses']
        for strategy_status in strategy_statuses:
            tmp_impl_status = {}
            tmp_s_a_status_assocation = {}
            for impl_status_struct_key in impl_status_struct_info:
                if strategy_status.has_key(impl_status_struct_key):
                    if strategy_status[impl_status_struct_key]:
                        tmp_impl_status[impl_status_struct_info[impl_status_struct_key]] = strategy_status[impl_status_struct_key]
                        tmp_s_a_status_assocation['STRATEGIC_ACTION_WID'] = strategy['id']
                        tmp_s_a_status_assocation['STRATEGIC_ACTION_ID'] = 99999
                        tmp_s_a_status_assocation['IMPL_STATUS_WID'] = strategy_status['sequence']
                        tmp_s_a_status_assocation['IMPL_STATUS_ID'] = 99999
            impl_status_info.append(tmp_impl_status)
            s_a_status_association_info.append(tmp_s_a_status_assocation)


        # OBJECTIVES_STRATEGIC_ACTIONS
        for objective_id in strategy['objective_ids']:
            #XXX EBC: FIX OBJECTIVE_ACT_WID
            objectives_strategies_info.append({ 'OBJECTIVE_WID'         : objective_id,
                                                'STRATEGIC_ACTION_WID'  : strategy['id'],
                                                'OBJECTIVE_ACT_WID'     : obj_strat_wid_count})
            obj_strat_wid_count += 1


        # STRATEGIC_ACTION_STEPS
        activities = strategy['activities']
        for activity in activities:
            tmp_activity = {}
            for actions_struct_key in actions_struct_info.keys():
                if activity.has_key(actions_struct_key):
                    if activity[actions_struct_key]:
                        tmp_activity[actions_struct_info[actions_struct_key]] = activity[actions_struct_key]
                        tmp_activity['STRATEGIC_ACTION_WID'] = strategy['id']
                        tmp_activity['STEP_WID'] = actions_count
            activities_info.append(tmp_activity)


            # IMPL_STATUS ( STRATEGIC_ACTION_STEPS entries into IMPL_STATUS require associations in STEP_STATUS_ASSOCIATIONS!!!!!! )
            activity_statuses = activity['statuses']
            for activity_status in activity_statuses:
                tmp_impl_status = {}
                tmp_step_status_assocation = {}
                for impl_status_struct_key in impl_status_struct_info:
                    if activity_status.has_key(impl_status_struct_key):
                        if activity_status[impl_status_struct_key]:
                            tmp_impl_status[impl_status_struct_info[impl_status_struct_key]] = activity_status[impl_status_struct_key]
                            tmp_step_status_assocation['STEP_WID'] = actions_count
                            tmp_step_status_assocation['STRATEGIC_ACTION_STEP_ID'] = 99999 # Database columns are 'not null' so populating with temp data
                            tmp_step_status_assocation['IMPL_STATUS_WID'] = activity_status['sequence']
                            tmp_step_status_assocation['IMPL_STATUS_ID'] = 99999 # Database columns are 'not null' so populating with temp data
                impl_status_info.append(tmp_impl_status)
                step_status_association_info.append(tmp_step_status_assocation)

            actions_count += 1


    # INDICATORS
    indicators = miradi_data_dict['indicators']
    indicator_struct_info = {   'id'            : 'INDICATOR_WID',
                                'name'          : 'INDICATOR_NAME',
                                'priority'      : 'PRIORITY',
                                'comment'       : 'INDICATOR_COMMENT',
                                }

    # INDICATOR_MEASURES
    indicator_measure_struct_info = {   'sequence'      :'IND_MEAS_WID',
                                        'measurement'   :'IND_MEAS_MEASURE',
                                        'comment'       :'IND_MEAS_COMMENT',
                                        'date'          :'IND_MEAS_DATE',
                                        'source'        :'IND_MEAS_SOURCE',
                                        'trend'         :'IND_MEAS_TREND',
                                        'rating'        :'IND_MEAS_RATING',
                                        }
    for indicator in indicators:
        other_count = 1
        tmp_indicator = {}
        for indicator_struct_key in indicator_struct_info.keys():
            if indicator.has_key(indicator_struct_key):
                if indicator[indicator_struct_key]:
                    tmp_indicator['INDICATOR_WID'] = indicator['id']
                    tmp_indicator['SHARED_IND_WID'] = indicator['id'] #This is needed for CAP but to be compatible, make same as id!
                    tmp_indicator[indicator_struct_info[indicator_struct_key]] = indicator[indicator_struct_key]
                    #OTHER (entries into OTHER require associations in INDICATORS_OTHER)
                    #XXX PA: Eric, please check me on my column assignments here, particularly in the INDICATORS_OTHER table.  Also,
                    #        I don't have the context here to populate TARGET_WID in the INDICATORS_OTHER table.  Is that a problem?
                    if (indicator['factor_type'] != 'Target') and (indicator['factor_type'] != 'DirectThreat'):
                        if (indicator['factor_name']):
                            other_info.append({ 'OTHER_WID'     : other_count,
                                                'OTHER_NAME'    : "%s: %s" % (indicator['factor_type'], indicator['factor_name']),
                                                })
                            indicators_other_info.append({  'INDICATOR_OTHER_WID'   : other_count,
                                                            'OTHER_WID'             : other_count,
                                                            'INDICATOR_WID'         : indicator['id'],
                                                            'TARGET_ID'             : -1,
                                                            'TARGET_WID'            : -1,
                                                            })
                            other_count += 1
        if tmp_indicator:
            indicator_info.append(tmp_indicator)


        # INDICATOR_MEASURES
        indicator_measure_count = 1
        indicator_measures = indicator['measures']
        for indicator_measure in indicator_measures:
            tmp_indicator_measure = {}
            for indicator_measure_stuct_key in indicator_measure_struct_info.keys():
                if indicator_measure.has_key(indicator_measure_stuct_key):
                    if indicator_measure[indicator_measure_stuct_key]:
                        tmp_indicator_measure['INDICATOR_WID'] = indicator['id']
                        tmp_indicator_measure['IND_MEAS_WID'] = str( indicator_measure_count )
                        tmp_indicator_measure[indicator_measure_struct_info[indicator_measure_stuct_key]] = indicator_measure[indicator_measure_stuct_key]
            indicator_measure_info.append(tmp_indicator_measure)
            indicator_measure_count += 1


        # INDICATOR_METHOD_ASSOCIATIONS
        indicator_methods_count = 1
        indicator_methods = indicator['method_ids']
        for indicator_method in indicator_methods:
            if indicator_method:
                indicator_methods_associations_info.append({'METHOD_WID'           : indicator_method,
                                                            'INDICATOR_WID'        : indicator['id'],
                                                            'INDICATOR_METHOD_WID' : indicator_methods_count,
                                                            })
                indicator_methods_count += 1


        # IMPL_STATUS ( INDICATORS entries into IMPL_STATUS require associations in INDICATOR_STATUS_ASSOCIATION!!!!!! )
        indicator_statuses = indicator['statuses']
        for indicator_status in indicator_statuses:
            tmp_impl_status = {}
            tmp_ind_status_assocation = {}
            for impl_status_struct_key in impl_status_struct_info:
                if indicator_status.has_key(impl_status_struct_key):
                    if indicator_status[impl_status_struct_key]:
                        tmp_impl_status[impl_status_struct_info[impl_status_struct_key]] = indicator_status[impl_status_struct_key]
                        tmp_ind_status_assocation['INDICATOR_WID'] = indicator['id']
                        tmp_ind_status_assocation['INDICATOR_ID'] = 99999
                        tmp_ind_status_assocation['IMPL_STATUS_WID'] = indicator_status['sequence']
                        tmp_ind_status_assocation['IMPL_STATUS_ID'] = 99999
            impl_status_info.append(tmp_impl_status)
            indicator_status_association_info.append(tmp_ind_status_assocation)


    #INDICATOR METHODS
    methods = miradi_data_dict['methods']
    method_struct_info = {  'id'            : 'METHOD_WID',
                            'name'          : 'METHOD_NAME',
                            'detail'        : 'METHOD_DETAIL',
                            'comment'       : 'METHOD_COMMENT',
                            }
    for method in methods:
        tmp_method = {}
        for method_struct_key in method_struct_info.keys():
            if method.has_key(method_struct_key):
                if method[method_struct_key]:
                    tmp_method[method_struct_info[method_struct_key]] = method[method_struct_key]
        if tmp_method:
            method_info.append(tmp_method)

    # all_data looks something like this:
    # all_data = { 'PROJECTS'              :   [{ 'PROJECT_NAME':name,
    #                                             'CONTACT_FNAME':firstname,
    #                                             'CONTACT_LNAME':lastname,
    #                                             'CONTACT_EMAIL':email,
    #                                             'SHARE_OUTSIDE_TNC':self._convertToYesNo( shareStatus ),
    #                                         },],
    #              'PROJECT_COUNTRIES'    :   countries,
    #              'PROJECT_OU'           :   ous,
    #             }
    # Where the dictionary keys are the actual DB table names/column names!
    all_data = {'PROJECTS'                      : [project_info,],
                'PROJECT_COUNTRIES'             : countries_info,
                'PROJECT_OU'                    : ous_info,
                'PROJECT_ECOREGIONS'            : ecoregion_info,
                'KEY_ATTRIBUTES'                : kea_info,
                'PROJECT_TARGETS'               : target_info,
                'PROJECT_HABITATS'              : t_hab_info,
                'NESTED_TARGETS'                : nested_target_info,
                'STRATEGIC_ACTION_THREATS'      : strat_act_threats_info,
                'STRESSES_TARGET'               : stress_info,
                'STRESS_THREAT'                 : stress_threat_info,
                'THREAT_TARGET'                 : threat_target_assocs_info,
                'VIABILITY'                     : viability_assocs_info,
                'THREATS'                       : threat_info,
                'INDICATOR_THREATS'             : threat_indicator_info,
                'PROJECT_OBJECTIVES'            : objective_info,
                'OBJECTIVE_INDICATORS'          : objective_indicator_info,
                'PCT_COMPLETE'                  : percent_complete_measures_info,
                'OBJ_PCT_COMPLETE_ASSOCIATIONS' : obj_percent_complete_assoc_info,
                'STRATEGIC_ACTIONS'             : strategy_info,
                'IMPL_STATUS'                   : impl_status_info,
                'S_A_STATUS_ASSOCIATIONS'       : s_a_status_association_info,
                'OBJECTIVES_STRATEGIC_ACTIONS'  : objectives_strategies_info,
                'STRATEGIC_ACTION_STEPS'        : activities_info,
                'STEP_STATUS_ASSOCIATIONS'      : step_status_association_info,
                'INDICATORS'                    : indicator_info,
                'OTHER'                         : other_info,
                'INDICATORS_OTHER'              : indicators_other_info,
                'INDICATOR_MEASURES'            : indicator_measure_info,
                'INDICATOR_METHOD_ASSOCIATIONS' : indicator_methods_associations_info,
                'INDICATOR_STATUS_ASSOCIATIONS' : indicator_status_association_info,
                'METHODS'                       : method_info,
                }

    return all_data

def convertMiradi1ToConPro2DataDict( miradi_data_dict ):

    # Keep variables outside of loops. These variables contain ALL the data for the tables in the database.
    all_data                            = {}
    project_info                        = {}
    countries_info                      = []
    ous_info                            = []
    ecoregion_info                      = []
    kea_info                            = []
    target_info                         = []
    t_hab_info                          = []
    nested_target_info                  = []
    strat_act_threats_info              = []
    stress_info                         = []
    stress_threat_info                  = []
    threat_target_assocs_info           = []
    viability_assocs_info               = []
    indicator_measure_info              = []
    threat_info                         = []
    objective_info                      = []
    objective_indicator_info            = []
    strategy_info                       = []
    impl_status_info                    = []
    s_a_status_association_info         = []
    objectives_strategies_info          = []
    activities_info                     = []
    indicator_info                      = []
    method_info                         = []
    indicator_methods_associations_info = []
    indicator_status_association_info   = []

    #PROJECTS table
    curr_branch = miradi_data_dict['project_info'][0]
    project_struct_info = {  'project_id'               : 'PROJECT_ID',
                             'parent_project_id'        : 'PARENT_PROJECT_ID',
                             'shareable'                : 'SHARE_OUTSIDE_TNC',
                             'project_name'             : 'PROJECT_NAME',
                             'start_date'               : 'PROJECT_START_DATE',
                             'latitude'                 : 'LATITUDE',
                             'longitude'                : 'LONGITUDE',
                             'givenname'                : 'CONTACT_FNAME',
                             'surname'                  : 'CONTACT_LNAME',
                             'email'                    : 'CONTACT_EMAIL',
                             'phone'                    : 'CONTACT_TELEPHONE',
                             'organization'             : 'CONTACT_ORGANIZATION',
                             'description_comment'      : 'PROJECT_DESCR_COMMENT',
                             'goal_comment'             : 'PROJECT_GOAL_COMMENT',
                             'hectares'                 : 'PROJECT_AREA_SIZE_HECTARES',
                             'planning_team_comment'    : 'PLANNING_TEAM_COMMENT',
                             'lessons_learned'          : 'PROJECT_LESSONS_LEARNED',
                             'stressless_threat_rank'   : 'STRESSLESS_THREAT_RANK',
                             'project_threat_rank'      : 'PROJECT_THREAT_RANK',
                             'project_viability_rank'   : 'PROJECT_VIA_RANK',
                             'exporter_version'         : 'WKBK_VERSION',
                             }
    for proj_item in project_struct_info.keys():
        if curr_branch.has_key(proj_item):
            # if curr_branch[proj_item] evals to true, then store.... we don't want empty strings and such.
            if curr_branch[proj_item]:
                project_info[project_struct_info[proj_item]] = curr_branch[proj_item]

            # Exceptions to normal handling here
            ## SHAREABLE
            if proj_item == 'shareable':
                if curr_branch['shareable'].lower() == 'false':
                    project_info[project_struct_info[proj_item]] = 'NO'
                elif curr_branch['shareable'].lower() == 'true':
                    project_info[project_struct_info['shareable']] = 'YES'
                else:
                    # XXX EBC: THis should check for 1/0 and that then should be rewritten to YES/NO
                    # DELETE THIS:
                    project_info[project_struct_info['shareable']] = curr_branch['shareable']
                    # And finally, as per user, if here, default to most conservative value of 0.

            ## exporter_version
            if proj_item == 'exporter_version':
                project_info[project_struct_info['exporter_version']] = 'Miradi %s' % curr_branch['exporter_version']
            else:
                project_info[project_struct_info['exporter_version']] = 'Miradi - No version specified'

    #PROJECT_COUNTRIES table
    countries = curr_branch['country_codes']
    for country in countries:
        if country:
            countries_info.append({'COUNTRY_CODE':country})


    #PROJECT_OU
    ous = curr_branch['ou_codes']
    for ou in ous:
        if ou:
            ous_info.append({'PROJECT_OU_ID':ou})


    #PROJECT_ECOREGIONS
    ecoregions = curr_branch['ecoregion_codes']
    for ecoregion in ecoregions:
        if ecoregion:
            ecoregion_info.append({'ECOREGION_CODE':ecoregion})



    #KEY_ATTRIBUTES
    keas = miradi_data_dict['keas']
    kea_struct_info = { 'id':'KEY_ATTRIBUTE_WID',
                        'category':'CATEGORY_NAME',
                        'name':'KEY_ATTRIBUTE_NAME',
                        }
    for kea in keas:
        tmp_kea = {}
        for kea_item in kea_struct_info.keys():
            if kea.has_key(kea_item):
                # if kea[kea_item] evals to true, then record.... we don't want empty strings.
                if kea[kea_item]:
                    tmp_kea['SHARED_KEA_WID'] = kea['id'] # Per dberg: This is needed for CAP but to be compatable, make same as id!
                    tmp_kea[kea_struct_info[kea_item]] = kea[kea_item]
        kea_info.append(tmp_kea)

    #PROJECT_TARGETS
    targets = miradi_data_dict['targets']
    target_struct_info = {  'id'                        : 'TARGET_WID',
                            'sequence'                  : 'TARGET_SEQ',
                            'name'                      : 'TARGET_NAME',
                            'description'               : 'FOCAL_TARGET_DESC',
                            'description_comment'       : 'FOCAL_TARGET_DESC_COMMENT',
                            'target_viability_comment'  : 'TARGET_VIABILITY_COMMENT',
                            'target_viability_rank'     : 'TARGET_VIABILITY_RANK',
                            }
    for target in targets:
        curr_target_id = target['id']
        tmp_target = {}
        for target_item in target_struct_info.keys():

            # XXX EBC: Paul, what are your thoughts here? Line 158 doesn't need to be executed with every iteration.
            #

            if target.has_key(target_item):
                # if target[target_item] evals to true, then fetch the data.... we don't want empty records!
                if target[target_item]:
                    #Exceptions
                    if target['target_viability_mode'] == 'simple':
                        #Note from Dan Salzer:
                        #   If the user has set the viability mode to Simple for a particular target,
                        #   the Miradi Overall Target Viability Rank for that target should be used to
                        #   populate both the ConPro Overall Target Viability Rank and the Condition
                        #   Override Rank.
                        # So, in addition to storing the value in PROJECT_TARGETS.TARGET_VIABILITY_RANK
                        # adding it to the override value of condition at PROJECT_TARGETS.CONDITION_OVRD_RANK
                        #
                        tmp_target['CONDITION_OVRD_RANK'] = target['target_viability_rank']
                        tmp_target['CONDITION_WGT'] = '1'
                        # If NOTE_VIA_RANK_OVERRIDE is not a part of the comment, add it.
                        try:
                            tmp_val = target['target_viability_comment']
                        except:
                            tmp_val = ''
                        if NOTE_VIA_RANK_OVERRIDE not in tmp_val:
                            tmp_target[target_struct_info['target_viability_comment']] = "%s  %s" % (tmp_val,NOTE_VIA_RANK_OVERRIDE)
                    tmp_target[target_struct_info[target_item]] = target[target_item]
        target_info.append(tmp_target)



        #PROJECT_HABITATS
        habitat_taxonomy_codes = target['habitat_taxonomy_codes']
        for habitat_taxonomy_code in habitat_taxonomy_codes:
            if habitat_taxonomy_code:
                t_hab_info.append( {'TARGET_WID':curr_target_id,'HABITAT_ASSOCIATION_CODE':habitat_taxonomy_code} )


        #NESTED_TARGETS
        nested_targets = target['nested_targets']
        nest_t_struct_info = {   'sequence' : 'NESTED_TARGET_SEQ',
                                 'name'     : 'NESTED_TARGET_NAME',
                                 'comment'  : 'NESTED_TARGET_COMMENT',
                                 }
        for nested_target in nested_targets:
            tmp_nested_target = {}
            for nest_t_struct_key in nest_t_struct_info.keys():
                if nested_target[nest_t_struct_key]:
                    tmp_nested_target['TARGET_WID'] = curr_target_id
                    tmp_nested_target[nest_t_struct_info[nest_t_struct_key]] = nested_target[nest_t_struct_key]
            nested_target_info.append(tmp_nested_target)


        #STRATEGIC_ACTION_THREATS
        strategy_threat_target_assocs = target['strategy_threat_target_assocs']
        strat_act_threats_struct_info = {   'strategy_id'   : 'STRATEGIC_ACTION_WID',
                                            'threat_id'     : 'THREAT_WID',
                                            }
        for strategy_threat_target_assoc in strategy_threat_target_assocs:
            tmp_strat_act_threats = {}
            for strat_act_threats_key in strat_act_threats_struct_info.keys():
                if strategy_threat_target_assoc.has_key(strat_act_threats_key):
                    if strategy_threat_target_assoc[strat_act_threats_key]:
                        tmp_strat_act_threats['TARGET_WID'] = curr_target_id
                        tmp_strat_act_threats[strat_act_threats_struct_info[strat_act_threats_key]] = strategy_threat_target_assoc[strat_act_threats_key]
            strat_act_threats_info.append(tmp_strat_act_threats)


        #STRESSES_TARGET
        stresses = target['stresses']
        stresses_struct_info = {'sequence'      : 'STRESS_TARGET_SEQ',
                                'name'          : 'STRESS_NAME',
                                'severity'      : 'STRESS_SEVERITY',
                                'scope'         : 'STRESS_SCOPE',
                                'to_target_rank': 'STRESS_TO_TARGET_RANK',
                                }
        for stress in stresses:
            tmp_stress = {}
            for stresses_struct_key in stresses_struct_info.keys():
                if stress.has_key(stresses_struct_key):
                    if stress[stresses_struct_key]:
                        tmp_stress['TARGET_WID'] = curr_target_id
                        tmp_stress[stresses_struct_info[stresses_struct_key]] = stress[stresses_struct_key]
            if tmp_stress:
                stress_info.append(tmp_stress)


            #STRESS_THREAT
            stresses_threats = stress['to_threat_ratings']
            stress_threat_struct_info = {   'threat_id'                     : 'THREAT_TARGET_SEQ',
                                            'contrib_rank'                  : 'S_T_CONTRIB_RANK',
                                            'irreversible_rank'             : 'S_T_IRREVERSIBLE_RANK',
                                            'stress_threat_to_target_rank'  : 'S_T_TO_TARGET_RANK',
                                            }
            for stress_threat in stresses_threats:
                tmp_stress_threat = {}
                for stress_threat_struct_key in stress_threat_struct_info.keys():
                    if stress_threat[stress_threat_struct_key]:
                        tmp_stress_threat['TARGET_WID'] = curr_target_id
                        tmp_stress_threat['THREAT_TARGET_SEQ'] = stress_threat['threat_id']
                        tmp_stress_threat['STRESS_TARGET_SEQ'] = stress['sequence']
                        tmp_stress_threat[stress_threat_struct_info[stress_threat_struct_key]] = stress_threat[stress_threat_struct_key]
                stress_threat_info.append(tmp_stress_threat)


        #THREAT_TARGET
        threat_target_assocs = target['threat_target_assocs']
        threat_target_assocs_struct_info = {'threat_id'             :'THREAT_WID',
                                            'threat_to_target_rank' :'THREAT_TO_TARGET_RANK',
                                            'severity'              :'THREAT_SEVERITY',
                                            'scope'                 :'THREAT_SCOPE',
                                            'irreversibility'       :'THREAT_IRREVERSIBILITY',
                                            'comment'               :'THREAT_TARGET_COMMENT',
                                            }
        for threat_target_assoc in threat_target_assocs:
            tmp_threat_target_assocs = {}
            for threat_target_assocs_struct_key in threat_target_assocs_struct_info.keys():
                if threat_target_assoc.has_key(threat_target_assocs_struct_key):
                    if threat_target_assoc[threat_target_assocs_struct_key]:
                        tmp_threat_target_assocs['TARGET_WID'] = curr_target_id
                        tmp_threat_target_assocs['THREAT_TARGET_SEQ'] = threat_target_assoc['threat_id']
                        tmp_threat_target_assocs[threat_target_assocs_struct_info[threat_target_assocs_struct_key]] = threat_target_assoc[threat_target_assocs_struct_key]
            threat_target_assocs_info.append(tmp_threat_target_assocs)


    #VIABILITY
    #Viability info is split into two tables for SEM:
        # VIABILITY
        # INDICATOR_MEASURES
    viability_count = 1
    indicator_measure_count = 1
    viability_assessments = miradi_data_dict['viability_assessments']
    viability_struct_info = {   'target_id'                         :'TARGET_WID',
                                'indicator_id'                      :'INDICATOR_WID',
                                'kea_id'                            :'KEY_ATTRIBUTE_WID',
                                'indicator_description_poor'        :'INDICATOR_DESC_POOR',
                                'indicator_description_fair'        :'INDICATOR_DESC_FAIR',
                                'indicator_description_good'        :'INDICATOR_DESC_GOOD',
                                'indicator_description_very_good'   :'INDICATOR_DESC_VERY_GOOD',
                                'desired_viability_rating'          :'DSRD_VIABILITY_RATING',
                                'desired_rating_date'               :'DSRD_RATING_DATE',
                                'kea_and_indicator_comment'         :'ATTR_AND_IND_COMMENT',
                                'indicator_rating_comment'          :'IND_RATINGS_COMMENT',
                                'desired_rating_comment'            :'DSRD_RATING_COMMENT',
                                'viability_record_comment'          :'VIA_RECORD_COMMENT',
                                }

    indicator_measure_stuct_info = {'indicator_id'                      :'INDICATOR_WID',
                                    'current_indicator_status_viability':'IND_MEAS_MEASURE',
                                    'current_viability_rating'          :'IND_MEAS_RATING',
                                    'current_rating_comment'            :'IND_MEAS_COMMENT',
                                    'current_rating_date'               :'IND_MEAS_DATE',
                                    'confidence_current_rating'         :'IND_MEAS_SOURCE',
                                    }
    for viability_assessment in viability_assessments:
        # VIABILITY
        tmp_viability = {}
        for viability_struct_key in viability_struct_info.keys():
            if viability_assessment.has_key(viability_struct_key):
                if viability_assessment[viability_struct_key]:
                    tmp_viability['VIABILITY_WID'] = str( viability_count )
                    tmp_viability[viability_struct_info[viability_struct_key]] = viability_assessment[viability_struct_key]
        viability_assocs_info.append(tmp_viability)
        viability_count += 1

        # INDICATOR_MEASURES
        tmp_indicator_measure = {}
        for indicator_measure_stuct_key in indicator_measure_stuct_info.keys():
            if viability_assessment.has_key(indicator_measure_stuct_key):
                if viability_assessment[indicator_measure_stuct_key]:
                    tmp_indicator_measure['IND_MEAS_WID'] = str( indicator_measure_count )
                    tmp_indicator_measure[indicator_measure_stuct_info[indicator_measure_stuct_key]] = viability_assessment[indicator_measure_stuct_key]
        indicator_measure_info.append(tmp_indicator_measure)
        indicator_measure_count += 1


    #THREATS
    threats = miradi_data_dict['threats']
    threat_struct_info = {  'id'                    :'THREAT_WID',
                            'name'                  :'THREAT_NAME',
                            'threat_taxonomy_code'  :'THREAT_TAXONOMY_CODE',
                            'threat_to_project_rank':'THREAT_TO_PROJ_RANK',
                            }
    for threat in threats:
        tmp_threat = {}
        for threat_struct_key in threat_struct_info.keys():
            if threat.has_key(threat_struct_key):
                if threat[threat_struct_key]:
                    tmp_threat['THREAT_RANK_SEQ'] = threat['id']
                    tmp_threat[threat_struct_info[threat_struct_key]] = threat[threat_struct_key]
        threat_info.append(tmp_threat)


    #PROJECT_OBJECTIVES
    objective_indicator_count = 1
    objectives = miradi_data_dict['objectives']
    objective_struct_info = {   'id':       'OBJECTIVE_WID',
                                'name':     'OBJECTIVE_NAME',
                                'comment':  'OBJECTIVE_COMMENT',
                                }
    for objective in objectives:
        tmp_objective = {}
        for objective_struct_key in objective_struct_info:
            if objective.has_key(objective_struct_key):
                if objective[objective_struct_key]:
                    tmp_objective['PRINT_ORDER'] = objective['id']
                    tmp_objective[objective_struct_info[objective_struct_key]] = objective[objective_struct_key]
        objective_info.append(tmp_objective)


        #OBJECTIVE_INDICATORS
        objective_indicators = objective['indicator_ids']
        for objective_indicator in objective_indicators:
            if objective_indicator:
                objective_indicator_info.append( {  'OBJ_IND_ASSOC_WID':objective_indicator_count,
                                                    'OBJECTIVE_WID':objective['id'],
                                                    'INDICATOR_WID':objective_indicator,} )
            objective_indicator_count += 1


    #STRATEGIC_ACTIONS
    impl_status_count = 1
    strategies = miradi_data_dict['strategies']
    strategy_struct_info = {'id'            :'STRATEGIC_ACTION_WID',
                            'name'          :'S_A_NAME',
                            'taxonomy_code' :'S_A_TAXONOMY_CODE',
                            'selected'      :'S_A_SELECTED',
                            'comment'       :'S_A_COMMENT',
                            }
    impl_status_struct_info = { 'status':'IMPL_STATUS_MEASURE', }
    actions_struct_info = { 'id':'STEP_WID',
                            'name':'STEP_NAME',
                            'start_date':'STEP_START_DATE',
                            'end_date':'STEP_END_DATE',
                            }

    obj_strat_wid_count = 1
    actions_count = 1
    for strategy in strategies:
        # STRATEGIC_ACTIONS
        tmp_strategy = {}
        for strategy_struct_key in strategy_struct_info.keys():
            if strategy.has_key(strategy_struct_key):
                if strategy[strategy_struct_key]:
                    tmp_strategy[strategy_struct_info[strategy_struct_key]] = strategy[strategy_struct_key]
        strategy_info.append(tmp_strategy)

        # IMPL_STATUS ( Entries into IMPL_STATUS require associations in S_A_STATUS_ASSOCIATIONS!!!!!! )
        for impl_status_struct_key in impl_status_struct_info:
            tmp_impl_status = {}
            tmp_s_a_status_assocation = {}
            if strategy.has_key(impl_status_struct_key):
                if strategy[impl_status_struct_key]:
                    #tmp_impl_status[]
                    tmp_impl_status[impl_status_struct_info[impl_status_struct_key]] = strategy[impl_status_struct_key]
                    tmp_impl_status['IMPL_STATUS_WID'] = impl_status_count
                    tmp_s_a_status_assocation['STRATEGIC_ACTION_WID'] = strategy['id']
                    tmp_s_a_status_assocation['STRATEGIC_ACTION_ID'] = 99999
                    tmp_s_a_status_assocation['IMPL_STATUS_WID'] = impl_status_count
                    tmp_s_a_status_assocation['IMPL_STATUS_ID'] = 99999
                    impl_status_count += 1
            impl_status_info.append(tmp_impl_status)
            s_a_status_association_info.append(tmp_s_a_status_assocation)


        # OBJECTIVES_STRATEGIC_ACTIONS
        for objective_id in strategy['objective_ids']:
            #XXX EBC: FIX OBJECTIVE_ACT_WID
            objectives_strategies_info.append({ 'OBJECTIVE_WID'         : objective_id,
                                                'STRATEGIC_ACTION_WID'  : strategy['id'],
                                                'OBJECTIVE_ACT_WID'     : obj_strat_wid_count})
            obj_strat_wid_count += 1

        #STRATEGIC_ACTION_STEPS
        activities = strategy['activities']
        for activity in activities:
            tmp_activity = {}
            for actions_struct_key in actions_struct_info.keys():
                if activity.has_key(actions_struct_key):
                    if activity[actions_struct_key]:
                        tmp_activity[actions_struct_info[actions_struct_key]] = activity[actions_struct_key]
                        tmp_activity['STRATEGIC_ACTION_WID'] = strategy['id']
                        tmp_activity['STEP_WID'] = actions_count
            actions_count += 1
            activities_info.append(tmp_activity)

    #INDICATORS
    indicator_methods_count = 1
    indicator_methods_assoc_count = 1
    indicators = miradi_data_dict['indicators']
    indicator_struct_info = {   'id'        : 'INDICATOR_WID',
                                'name'      : 'INDICATOR_NAME',
                                'priority'  : 'PRIORITY',
                                'comment'   : 'INDICATOR_COMMENT',
                                }

    for indicator in indicators:
        tmp_indicator = {}
        tmp_method = {}
        tmp_impl_status = {}
        tmp_indicator_status_assoc = {}
        for indicator_struct_key in indicator_struct_info.keys():
            if indicator.has_key(indicator_struct_key):
                if indicator[indicator_struct_key]:
                    tmp_indicator['SHARED_IND_WID'] = indicator['id'] #This is needed for CAP but to be compaitible, make same as id!
                    tmp_indicator[indicator_struct_info[indicator_struct_key]] = indicator[indicator_struct_key]
        if tmp_indicator:
            indicator_info.append(tmp_indicator)


        #INDICATOR METHODS ( Entries into METHODS require associations in INDICATOR_METHOD_ASSOCIATIONS!!!!!! )
        if indicator['methods']:
            tmp_method['METHOD_NAME'] = indicator['name']
            tmp_ind_methods_detail = indicator['methods']
            if 'Freq/Timing:' in tmp_ind_methods_detail:
                tmp_ind_methods_detail = tmp_ind_methods_detail.split('Freq/Timing:')[0]
            if 'Location:' in tmp_ind_methods_detail:
                tmp_ind_methods_detail = tmp_ind_methods_detail.split('Location:')[0]
            if 'Who Monitors:' in tmp_ind_methods_detail:
                tmp_ind_methods_detail = tmp_ind_methods_detail.split('Who Monitors:')[0]
            if 'Cost Override:' in tmp_ind_methods_detail:
                tmp_ind_methods_detail = tmp_ind_methods_detail.split('Cost Override:')[0]
            if 'Funding Source:' in tmp_ind_methods_detail:
                tmp_ind_methods_detail = tmp_ind_methods_detail.split('Funding Source:')[0]
            if 'Monitor Plan:' in tmp_ind_methods_detail:
                tmp_ind_methods_detail = tmp_ind_methods_detail.split('Monitor Plan:')[0]
            tmp_method['METHOD_DETAIL'] = tmp_ind_methods_detail.strip()
        if indicator['annual_cost']:
            try:
                tmp_method['ANNUAL_COST'] = float( indicator['annual_cost'] )
            except:
                pass
        if indicator['who_monitors']:
            tmp_method['WHO_MONITORS'] = indicator['who_monitors']
        if tmp_method:
            tmp_method['METHOD_WID'] = indicator_methods_count
            method_info.append(tmp_method)
            indicator_methods_associations_info.append({'METHOD_WID'           : indicator_methods_count,
                                                        'INDICATOR_WID'        : indicator['id'],
                                                        'INDICATOR_METHOD_WID' : indicator_methods_assoc_count,
                                                        })
            indicator_methods_count += 1
            indicator_methods_assoc_count += 1

        #INDICATOR STATUS (IMPL STATUS) ( Entries into IMPL_STATUS require associations in INDICATOR_STATUS_ASSOCIATION!!!!!! )
        if indicator['status']:
            tmp_impl_status['IMPL_STATUS_MEASURE'] = indicator['status']
            tmp_impl_status['IMPL_STATUS_WID'] = impl_status_count
            impl_status_info.append( tmp_impl_status )
            indicator_status_association_info.append({  'INDICATOR_WID': indicator['id'],
                                                        'INDICATOR_ID': 99999,
                                                        'IMPL_STATUS_WID':impl_status_count,
                                                        'IMPL_STATUS_ID': 99999,
                                                        })
            impl_status_count += 1

    # all_data looks something like this:
    # all_data = { 'PROJECTS'              :   [{ 'PROJECT_NAME':name,
    #                                             'CONTACT_FNAME':firstname,
    #                                             'CONTACT_LNAME':lastname,
    #                                             'CONTACT_EMAIL':email,
    #                                             'SHARE_OUTSIDE_TNC':self._convertToYesNo( shareStatus ),
    #                                         },],
    #              'PROJECT_COUNTRIES'    :   countries,
    #              'PROJECT_OU'           :   ous,
    #             }
    # Where the dictionary keys are the actual DB table names/column names!
    all_data = {'PROJECTS'                      : [project_info,],
                'PROJECT_COUNTRIES'             : countries_info,
                'PROJECT_OU'                    : ous_info,
                'PROJECT_ECOREGIONS'            : ecoregion_info,
                'KEY_ATTRIBUTES'                : kea_info,
                'PROJECT_TARGETS'               : target_info,
                'PROJECT_HABITATS'              : t_hab_info,
                'NESTED_TARGETS'                : nested_target_info,
                'STRATEGIC_ACTION_THREATS'      : strat_act_threats_info,
                'STRESSES_TARGET'               : stress_info,
                'STRESS_THREAT'                 : stress_threat_info,
                'THREAT_TARGET'                 : threat_target_assocs_info,
                'VIABILITY'                     : viability_assocs_info,
                'INDICATOR_MEASURES'            : indicator_measure_info,
                'THREATS'                       : threat_info,
                'PROJECT_OBJECTIVES'            : objective_info,
                'OBJECTIVE_INDICATORS'          : objective_indicator_info,
                'STRATEGIC_ACTIONS'             : strategy_info,
                'MIRADI_IMPL_STATUS'            : impl_status_info,
                'S_A_STATUS_ASSOCIATIONS'       : s_a_status_association_info,
                'OBJECTIVES_STRATEGIC_ACTIONS'  : objectives_strategies_info,
                'STRATEGIC_ACTION_STEPS'        : activities_info,
                'INDICATORS'                    : indicator_info,
                'METHODS'                       : method_info,
                'INDICATOR_METHOD_ASSOCIATIONS' : indicator_methods_associations_info,
                'INDICATOR_STATUS_ASSOCIATIONS' : indicator_status_association_info,
                }

    return all_data
